import 'package:flutter/material.dart';
import '../view/common_top_view.dart';
import '../view/product_title_view.dart';
import '../../manger/network_utils.dart';
import '../../models/serach_info_model.dart';
import '../view/product_coupon_view.dart';
import '../../models/yh_info_model.dart';
import '../../services/yh_info_manger.dart';
import '../view/product_chong_view.dart';
import '../view/product_htmldesc_view.dart';
import '../controller/comment_page.dart';
import '../view/product_common_view.dart';
import '../../components/loading_widget.dart';
import '../view/product_bottom.view.dart';
import '../../components/currency_select_widget.dart';
import 'package:ninetyfour/manger/user_manger.dart';
import '../../services/home_info_manager.dart';
import '../../models/home_init_model.dart';
import '../view/detail_popcoupon_view.dart';
import '../../manger/checkspu_utils.dart';
import '../../components/toast_utils.dart';
import '../../components/custom_dialog.dart';
import '../../l10n/app_localizations.dart';
import '../controller/confirm_page.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/umevent_utils.dart';
import '../../class/controller/product_no_page.dart';

class ProductDetailPage extends StatefulWidget {
  final int spuId;
  final int categoryId;

  const ProductDetailPage({
    Key? key,
    this.spuId = 0,
    this.categoryId = 0,
  }) : super(key: key);

  @override
  _ProductDetailPageState createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends State<ProductDetailPage> {
  final ValueNotifier<bool> loadingNotifier = ValueNotifier(false);
  bool _showCurrencySelect = false;
  bool _showCouponPopup = false;
  RechargeTypeModel? _model;
  List<CouponDeListModel>? couponInfoModel;
  List<CouponListModel>? discounfoModel;
  ReListModel? selectedModel;
  List<CurrencyListModel> currencyList = [];
  int selectPath = 0;
  int selectIndex = 0;
  bool isDiscount = false;
  int productNum = 1;
  String producttype = "普通商品";
  CommentArrayModel? commentInfoModel;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => loadData());
    final homeManager = HomeInfoManager();
    currencyList = homeManager.homeInitModel?.currencyList ?? [];
    UmengEvent.trackEvent("goodsdetail_launch","进入商品详情页","");
  }

  Future<void> loadData() async {
    if (loadingNotifier.value) return;

    loadingNotifier.value = true;
    Map<String, dynamic> param = widget.categoryId > 0
        ? {"categoryId": widget.categoryId}
        : {"spuId": widget.spuId};

    try {
      final response = await NetworkUtils.post(
        isSimplifiedChinese() ? RequestCmd.searchDetail : RequestCmd.searchListen,
        body: param,
      );

      final model = SearchDetailModel.fromJson(response);

      if (model.code == 200) {
        setState(() {
          _model = model.data;
          selectedModel = _model?.rechargeTypeList[selectPath].spuList[selectIndex];
        });
        loadData2();
        _loadComments();
      } else if (model.code == 500){
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ProductNoPage()),
        );
      } 
      else {
        // 处理错误状态
      }
    } catch (e) {
      print('Error loading page list: $e');
    } finally {
      loadingNotifier.value = false;
    }

  }

  Future<void> _loadComments() async {
    try {
      final response = await NetworkUtils.get(
        RequestCmd.commentPage,
        params: {"categoryId": _model?.categoryId,"pageSize":99999,"pageNum":1},
      );

      final model = CommentPageModel.fromJson(response);
      
      if (model.code == 200) {
        setState(() {
          commentInfoModel = model.data;
        });
      } else {
        setState(() {
        
        });
      }
    } catch (e) {
      setState(() {
       
      });
    }
  }

  Future<void> loadData2() async {

    final result = await CouponInfoManager().loadInfoData();
    if (result.success) {
      setState(() {
        couponInfoModel = result.couponInfoModel;
      });
    }
    loadData3();
  }

  Future<void> loadData3() async {
    final result2 = await DiscountManger().loadDiscountData(selectedModel!.spuId);
    if (result2.success) {
      try {
        final response = await NetworkUtils.post(
          RequestCmd.myCoupon,
          body: {"spuId": selectedModel!.spuId,"num": productNum,"status": 3},
        );
        final model = CouponModel.fromJson(response);
        if (model.code == 200) {
          setState(() {
            // isDiscount = model.data.isNotEmpty ? true : false;
            if (result2.discountModel!.isNotEmpty) {
              discounfoModel = result2.discountModel;
              isDiscount = true;
            } else {
              discounfoModel = [];
              isDiscount = false;
            }
          });
        } else {
          setState(() {
            isDiscount = false;
          });
        }
      } catch (e) {
        setState(() {
          isDiscount = false;
          discounfoModel = result2.discountModel;
        });
      } finally {
      }
    }
  }

  // 检查商品是否可以购买
  Future<void> checkspu(BuildContext context) async {
    UmengEvent.trackEvent("goodsdetail_buy","商品详情页点击立即购买", selectedModel!.spuId.toString());
    ToastUtils.showLoadingToast(context);
    final result = await CheckSpuConfig().checkSpuConfigWithId(selectedModel!.spuId.toString());
    if (result) {
      final result2 = await CheckSpuConfig().checkMaxcoinWithId(selectedModel!.spuId, productNum);
      ToastUtils.dismissLoadingToast();
      if (result2['success']) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ConfirmPage(selectedModel: selectedModel!,pricenum: productNum,producttype: producttype)),
        );
      }else{
        _showLogoutDialog(context,result2['message']);
      }
      // 处理成功逻辑
    } else {
      ToastUtils.dismissLoadingToast();
      _showLogoutDialog(context,AppLocalizations.of(context)!.valueReachedLimitr);
    }
  }

  void _showLogoutDialog(BuildContext context,String desc) {
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        title: AppLocalizations.of(context)!.orderfail,
        description: desc,
        leftButtonText: AppLocalizations.of(context)!.cancel,
        rightButtonText: AppLocalizations.of(context)!.confirm,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: () {
          Navigator.pop(context);
        },
      ),
    );
  }

@override
Widget build(BuildContext context) {
  final bottomPadding = MediaQuery.of(context).padding.bottom + 120;

  return Scaffold(
    appBar: CommonTopView(
      onPop: () => Navigator.pop(context),
      onPushContact: () {
        QYSDK.showQYSession();
      },
      onShowUnfold: (isUnfold) => setState(() => _showCurrencySelect = isUnfold),
      isUnfold: _showCurrencySelect,
    ) as PreferredSizeWidget,
    body: Stack(
      children: [
        // 主页面内容
        ValueListenableBuilder<bool>(
          valueListenable: loadingNotifier,
          builder: (context, isLoading, _) {
            return SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              clipBehavior: Clip.none,
              padding: EdgeInsets.only(bottom: bottomPadding),  // 留出底部空间
              child: Column(
                children: [
                  ProductTitleView(
                    model: selectedModel,
                    productModel: _model,
                    name: _model?.rechargeTypeList[selectPath].name ?? '',
                  ),
                  ProductCouponView(
                    couponInfoModel: couponInfoModel,
                    onCouponClick: () {
                      setState(() {
                        _showCouponPopup = true;
                      });
                    },
                  ),
                  if (_model?.rechargeTypeList != null)
                    ProductChongView(
                      rechargeTypeList: _model!.rechargeTypeList,
                      onSelect: (pathIndex, itemIndex) {
                        setState(() {
                          selectPath = pathIndex;
                          selectIndex = itemIndex;
                          producttype = _model?.rechargeTypeList[selectPath].name?? "普通商品";
                          selectedModel = _model?.rechargeTypeList[selectPath].spuList[selectIndex];
                          loadData3();
                        });
                      },
                    ),
                  ProductHtmlDescView(htmlContent: _model?.detail),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CommentPage(
                            categoryId: _model?.categoryId ?? '0',
                          ),
                        ),
                      );
                    },
                    child: commentInfoModel != null
                        ? CommentView(commentInfoModel: commentInfoModel!)
                        : const SizedBox.shrink(), // 或者加个加载中占位
                  ),

                  SizedBox(height: 15),
                ],
              ),
            );
          },
        ),
        LoadingWidget(isLoading: loadingNotifier),
        // ProductBottomView 固定在屏幕底部
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: ProductBottomView(
            selectedModel: selectedModel,
            couponInfoModel: discounfoModel,
            productNum: productNum,
            isDiscount: isDiscount,
            isSelect: _model?.sellOut == 1 ? true : false,
            onProductNumChanged: (value) {
              setState(() {
                productNum = value;
              });
              loadData3();
            },
            onTap: () async {
              checkspu(context);
            },
          ),
        ),
        // CurrencySelectWidget 覆盖底部的 ProductBottomView
        if (_showCurrencySelect)
          Positioned.fill(
            child: Material(
              color: Colors.transparent,  // 透明背景
              child: CurrencySelectWidget(
                currencyList: currencyList,
                top: 0,  // 完全覆盖在页面上
                onSelect: (selectedCurrency) {
                  setState(() {
                    _showCurrencySelect = false;
                    UserInfos.shared.currencyListModel = selectedCurrency;
                    loadData();
                  });
                },
              ),
            ),
          ),
        if (_showCouponPopup)
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            child: DetailPopCouponView(
              onClose: () => setState(() => _showCouponPopup = false),
              onRefresh: loadData2,
            ),
          ),
      ],
    ),
  );
}

}
